<?php

namespace App\Lib;

use Illuminate\Support\Facades\Log;
use RongCloud\RongCloud;

class rc
{
    private $rc_handle = NULL;

    public function __construct()
    {
        //单例
        if (is_null($this->rc_handle)) {
            $config = config('rong_cloud');
            $this->rc_handle = new RongCloud($config['appKey'], $config['appSecret']);
        }
    }

    /**
     * 用户注册 获取token
     *
     * @param int $userId 用户ID
     * @param string $nickname 用户昵称
     * @param string $image 用户头像
     *
     * @return string
     * */
    //old func
//    public function get_token($userId, $nickname, $image)
//    {
//        $params = [
//            'id' => $userId,
//            'name' => $nickname,
//            'portrait' => $image,
//        ];
//
//        $result = $this->rc_handle->getUser()->register($params);
//
//        // [
//        //     "code" => 200,
//        //     "userId" => "ujadk90ha",
//        //     "token" => "SfJQnrPDLZNMxSl+cNLZNMxSl+cNGDRLrkqw5cNGDRLrkqw5Xap7yf5"
//        // ];
//
//        return $result['token'];
//    }

    public function get_token($userId, $nickname, $image ,$uuid = 0)
    {
        $nickname = !empty($nickname) ? mb_substr($nickname ,0 ,32 ,'utf-8') : '';
        $params = [
            'id' => $userId,
            'name' => empty($nickname) ? $uuid : $nickname,
            'portrait' => $image,
        ];

        $result = $this->rc_handle->getUser()->register($params);
        if ($result['code'] != 200){
            write_log('RongLoginLog','ErrorParams',json_encode($params,JSON_UNESCAPED_UNICODE));
            write_log('RongLoginLog','ErrorRes',json_encode($result,JSON_UNESCAPED_UNICODE));
        }

        // [
        //     "code" => 200,
        //     "userId" => "ujadk90ha",
        //     "token" => "SfJQnrPDLZNMxSl+cNLZNMxSl+cNGDRLrkqw5cNGDRLrkqw5Xap7yf5"
        // ];

        return $result['code'] == 200 ? $result['token'] : '';
    }

    /**
     * 用户信息更新
     *
     * @param int $userId 用户ID
     * @param string $nickname 用户昵称
     * @param string $image 用户头像
     *
     * @return bool
     * */
    public function refresh($userId, $nickname, $image)
    {
        $params = [
            'id' => $userId,
            'name' => $nickname,
            'portrait' => $image,
        ];

        $result = $this->rc_handle->getUser()->update($params);

        // [
        //     "code" => 200,
        // ];

        return $result['code'] == 200;
    }


    /**
     * 发送单聊消息
     *
     * @param int $fromUserId 发送人ID
     * @param int $toUserId 接收人ID
     * @param string $objectName 消息类型(kk:sys_text_msg)
     * @param array $content 消息体数据
     * @param int $isIncludeSender 发送者自己是否接收此条消息  默认0: 不接收, 1: 接收
     *
     * @return bool
     */
    public function send_private_msg($fromUserId, $toUserId, $objectName, $content, $isIncludeSender = 1,$isPersisted = 1)
    {
        $params = [
            'senderId' => $fromUserId,
            'targetId' => $toUserId,
            "objectName" => $objectName,
            'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
            'isIncludeSender' => $isIncludeSender,
            'isPersisted' => $isPersisted,
        ];

        // write_log(
        //     'MsgCompoment'.(isCli()?'-cli':''),
        //     '[INFO] 亲密值变动消息-发送',
        //     $params
        // );
        $result = $this->rc_handle->getMessage()->Person()->send($params);

        // [
        //     "code" => 200,
        // ];

        return $result['code'] == 200;
    }

    /**
     * 发送系统消息
     *
     * @param int $fromUserId 发送人ID
     * @param int $toUserId 接收人ID
     * @param string $objectName 消息类型（自定义：kk:sys_text_msg）
     * @param array $content 消息体数据
     *
     * @return bool
     */
    public function send_system_msg($fromUserId, $toUserId, $objectName, $content, $pushContent = '', $pushData = '')
    {
        $params = [
            'senderId' => $fromUserId,
            'targetId' => $toUserId,
            "objectName" => $objectName,
            'content' => $content,
        ];
        if ($pushContent) {
            $params['pushContent'] = $pushContent;
        }
        if ($pushData) {
            $params['pushData'] = $pushData;
            $params['content']['extra'] = $pushData;
        }
        
        $result = $this->rc_handle->getMessage()->System()->send($params);


        return $result['code'] == 200;
    }

    /**
     * 系统消息：发送广播 (给应用内所有用户发送消息)
     *
     * @param int $fromUserId 发送人ID
     * @param string $objectName 消息类型（自定义：kk:xx）
     * @param array $content 消息体数据
     *
     * todo 参数废弃 @param int $platformId 0.全发、1.IOS、2.Android
     *
     * @return bool
     */
    public function broadcast($fromUserId, $objectName, $content, $platformId, $pushContent='', $pushData='')
    {
        $params = [
            'senderId' => $fromUserId,
            "objectName" => $objectName,
            'content' => $content,
        ];
        if ($pushContent) {
            $params['pushContent'] = $pushContent;
        }
        if ($pushData) {
            $params['pushData'] = $pushData;
            $params['content']['extra'] = $pushData;
        }
        $result = $this->rc_handle->getMessage()->System()->broadcast($params);

        // [
        //     "code" => 200,
        // ];

        return $result['code'] == 200;
    }

    /**
     * 创建聊天室
     * @param int $chatRoomId 聊天室ID
     * @param string $chatRoomName 聊天室名称
     *
     * @return bool
     */
    public function create_chat_room($chatRoomId, $chatRoomName)
    {
        $params = [
            'id' => $chatRoomId,
            'name' => $chatRoomName,
        ];

        $result = $this->rc_handle->getChatroom()->create($params);

        // [
        //     "code" => 200,
        // ];

        return $result['code'] == 200;
    }

    /**
     * todo 不存在此功能 已废弃 加入聊天室
     *
     * @param int $userId 用户ID
     * @param int $chatRoomId 聊天室ID
     *
     * @return bool
     * */
    public function join_chat_room($userId, $chatRoomId)
    {
        return true;
    }

    /**
     * 设置聊天室保活
     *
     * @param int $chatRoomId 聊天室ID
     *
     * @return bool
     */
    public function chat_room_keepalive($chatRoomId)
    {
        return true;
    }

    /**
     * 取消聊天室保活
     *
     * @param int $chatRoomId 聊天室ID
     *
     * @return bool
     */
    public function chat_room_unkeepalive($chatRoomId)
    {
        return true;
    }

    /**
     * 查询聊天室信息
     *
     * @param int $chatRoomId 聊天室ID
     *
     * @return bool
     */
    public function query_chat_room(int $chatRoomId)
    {
        $params = [
            'id' => $chatRoomId,
            'count' => 1, // 聊天室成员信息数，最多返回 500 个成员
            'order' => 1, // 查询聊天室成员顺序， 1: 加入时间正序 2: 加入时间倒序
        ];

        $result = $this->rc_handle->getChatroom()->get($params);

        // [
        //     "code" => 200,
        //     "total" => 100,
        //     "members" => [
        //        [
        //             "id" => "member1",
        //             "time" => "2018-03-08 16:38:26",
        //         ],
        //         [
        //             "id" => "member2",
        //             "time" => "2018-03-08 16:38:26"
        //         ]
        //      ]
        // ];

        return $result['code'] == 200 && !empty($result['members']);
    }

    /**
     * 发送聊天室消息
     *
     * @param int $fromUserId 发送人ID
     * @param int $toChatRoomId 聊天室ID
     * @param string $objectName 消息类型(kk:xx)
     * @param array $content 消息体数据
     *
     * @return bool
     */
    public function publish_chat_room($fromUserId, $toChatRoomId, $objectName, $content)
    {
        if (is_array($content)) {
            $content = json_encode($content, true);
        }

        $params = [
            'senderId' => $fromUserId,
            'targetId' => $toChatRoomId,
            "objectName" => $objectName,
            'content' => $content,
        ];
        $result = $this->rc_handle->getMessage()->Chatroom()->send($params);
        write_log(
            'sendFullScreen',
            '[INFO] publish_chat_room',
            [$params, $result]
        );
//         write_log(
//             'sendFullScreen'.(isCli()?'-cli':''),
//             '[INFO] 发送飘萍-publish_chat_room',
//             [$params, $result]
//         );

        // [
        //     "code" => 200,
        // ];

        return $result['code'] == 200;
    }

    /**
     * 默认指定客服 发送房间内消息
     *
     * @param int $toChatRoomId 聊天室ID
     * @param array $content 消息体数据
     *
     * @return bool
     */
    public function send_room_msg($toChatRoomId, $content)
    {
        if (is_array($content)) {
            $content = json_encode($content, true);
        }

        $params = [
            'senderId' => 11,
            'targetId' => $toChatRoomId,
            "objectName" => 'kk:audio_room',
            "isPersisted" => 0,
            'content' => $content,
        ];
        try{
//             write_log('rongcloud', '发送房间内消息:request', $params);
	//	var_dump($params['content']);exit();
		$result = $this->rc_handle->getMessage()->Chatroom()->send($params);
//             write_log('rongcloud', '发送房间内消息:response', $result);
	}catch (\Exception $e){
            write_log('error-rongcloud', '发送房间内消息失败:result', ['params' => $params, 'error' => $e->getMessage()]);
        }

        return $result['code'] == 200;
    }
    public function send_room_msg2($toChatRoomId, $content)
    {
        if (is_array($content)) {
            $content = json_encode($content, true);
        }

        $params = [
            'senderId' => 11,
            'targetId' => $toChatRoomId,
            "objectName" => 'kk:audio_room',
            "isPersisted" => 0,
            'content' => $content,
        ];
        try{
//             write_log('rongcloud', '发送房间内消息:request', $params);
            //	var_dump($params['content']);exit();
            $result = $this->rc_handle->getMessage()->Chatroom()->send($params);
//             write_log('rongcloud', '发送房间内消息:response', $result);
        }catch (\Exception $e){
            write_log('rongcloud', '发送房间内消息失败:result', ['params' => $params, 'result' => $result, 'error' => $e->getMessage()]);
        }

        return $result['code'] == 200;
    }
    /**
     * 邂逅内消息
     * @param $meetId
     * @param $content
     * @return bool
     */
    public function sendMeetMsg($meetId, $content){
        $params = [
            'senderId' => 11,
            'targetId' => $meetId,
            "objectName" => 'kk:meet_room',
            'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
        ];

        $result = $this->rc_handle->getMessage()->Chatroom()->send($params);

        // [
        //     "code" => 200,
        // ];

        return $result['code'] == 200;
    }

    /**
     * 群组 房间 消息
     * @param $targetId
     * @param $content
     * @param $objectName
     * @return bool
     */
    public function sendGroupChatRoomMsg($targetId, $content, $objectName): bool
    {
        $params = [
            'senderId' => 11,
            'targetId' => $targetId,
            'objectName' => $objectName,
            'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
        ];
        $result = $this->rc_handle->getMessage()->Chatroom()->send($params);
        return $result['code'] == 200;
    }
}
